//
//  XYComposePopView.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/3.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit
import pop
class XYComposePopView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    // 借口: 需要弹出的控制器
    var target: UIViewController?
    
    private lazy var bgImageView: UIImageView = {
        
        let imageView = UIImageView(image: UIImage.getScreenShotImage().applyLightEffect())
        imageView.userInteractionEnabled = true
        return imageView
    }()
    // 按钮容器
    private lazy var btns: [UIButton] = [UIButton]()
    private func setUpUI() {
        frame.size = CGSizeMake(kSCREENWITH, kSCREENHEIGHT)
        // 添加大图 // 苹果自带的磨砂处理效果
        
        addSubview(bgImageView)
        addSubview(sloganImage)
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        // 添加6个按钮
        addButtons()
    }
    private func addButtons(){
        
        let btnW: CGFloat = 80
        let btnH: CGFloat = 110
        // 间距
        let btnMargin = (kSCREENWITH - 3 * btnW) / 4
        
        // 读取plist文件
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let btnInfoes = NSArray(contentsOfFile: path)!
        
        for (i,value) in btnInfoes.enumerate() {
            
            let button = XYComposeBtn()
            
            // 添加点击事件
            button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            // 设置数据
            let dict = value as! NSDictionary
            
            // 读取图片名字
            let iconName = dict["icon"]! as! String
            // 标题
            let title = dict["title"]! as! String
            button.setImage(UIImage(named: iconName), forState: UIControlState.Normal)
            button.setTitle(title, forState: UIControlState.Normal)
            
            // 取到当前遍历的按钮的第 xx 行和 第 xx 列
            let col = i % 3
            let row = i / 3
            // 计算位置
            let childButtonX = CGFloat(col + 1) * btnMargin + CGFloat(col) * btnW
            let childButotnY = (btnH + btnMargin) * CGFloat(row) + kSCREENHEIGHT
            // 设置 frame
            button.frame = CGRect(x: childButtonX, y: childButotnY, width: btnW, height: btnH)
            addSubview(button)
            btns.append(button)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 懒加载控件
    private lazy var sloganImage: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    // 外部借口
    func show(target:UIViewController){
        
        self.target = target
        
        target.view.addSubview(self)
    }
    @objc private func childButtonClick(button:UIButton) {
        
        // 单个按钮放大 其他缩小
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for btn in self.btns {
                btn.alpha = 0.1
                if btn == button {
                    button.transform = CGAffineTransformScale(button.transform, 2, 2)
                }else{
                    btn.transform = CGAffineTransformScale(btn.transform, 0.2, 0.2)
                }
            }
        }) { (_) -> Void in
            
            // 弹出所需控制器 : 根据 控制器字符串获取目标控制器
            if let type = NSClassFromString("WeiboSourceCode.XYComposeController") as? UIViewController.Type {
                let instance = type.init()
                self.target?.presentViewController(XYNavController(rootViewController:instance), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
            }
        }
    }
    // 当控件移动到window 时调用
    override func willMoveToWindow(newWindow: UIWindow?) {
        for (index,btn) in btns.enumerate() {
            
            doAnimation(btn, index: index, isUp: true)
        }
    }
    private func doAnimation(button:UIButton,index:Int,isUp:Bool){
        // 创建动画
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        // 设置动画y 的移动方向
        var y = button.center.y + 350
        if isUp {
            y = button.center.y - 350
        }
        animation.toValue = NSValue(CGPoint: CGPointMake(button.center.x, y))
        // 设置弹性度 [0,20]，越大，幅度越大
        animation.springBounciness = 10
//        弹性速度：[0,20] 越小，执行的时候时间越长
        animation.springSpeed = 8
        // 通过当前系统的绝对时间CACurrentMediaTime() 和下标 计算动画开始的时间
        animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        // 给按钮添加动画
        button.pop_addAnimation(animation, forKey: nil)
        
    }
    // 点击非按钮区域取消
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        // 反向遍历 给按钮执行向下动画
        for (index,btn) in btns.reverse().enumerate() {
            
            doAnimation(btn, index: index, isUp: false)
            
        }
        // swift中的GCD延时操作
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
        
    }
}
